package com.qili.controller.supervisor;

import cn.hutool.core.util.IdUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.qili.base.entity.CurrentUser;
import com.qili.controller.sys.SysUserWorkExperienceController;
import com.qili.core.annotation.Log;
import com.qili.core.utils.DictTypes;
import com.qili.entity.affaircase.AffairCase;
import com.qili.entity.base.BaseCompany;
import com.qili.entity.base.BaseDict;
import com.qili.entity.supervisor.ProjectNotice;
import com.qili.entity.supervisor.SupervisorFile;
import com.qili.entity.supervisor.SupervisorProject;
import com.qili.entity.supervisor.dto.SupervisorProjectDTO;
import com.qili.entity.supplier.ProjectPlace;
import com.qili.entity.supplier.dto.ProjectPlaceDTO;
import com.qili.entity.sys.*;
import com.qili.entity.sys.dto.SysUserDTO;
import com.qili.exception.MyException;
import com.qili.service.SysUserService;
import com.qili.service.base.BaseCompanyService;
import com.qili.service.base.BaseDictService;
import com.qili.service.supervisor.ProjectNoticeServie;
import com.qili.service.supervisor.SupervisorFileService;
import com.qili.service.supplier.ProjectPlaceService;
import com.qili.service.sys.*;
import com.qili.util.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.assertj.core.util.Arrays;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import tk.mybatis.mapper.entity.Example;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.*;

import static java.util.Objects.isNull;

/**
 * @author zhaoyongke
 * @date 2020/10/28
 * @description
 */

@Controller
@Slf4j
@RequestMapping("/sys/personCenter")
public class PersonCenterController {

    @Autowired
    SysUserService userService;
    @Autowired
    BaseDictService baseDictService;
    @Autowired
    SysRegionService sysRegionService;
    @Autowired
    SupervisorFileService supervisorFileService;
    @Autowired
    UploadUtil uploadUtil;
    @Autowired
    private BaseCompanyService companyService;
    @Autowired
    private SysUserProjectService sysUserProjectService;
    @Autowired
    private SysUserWorkExperienceService sysUserWorkExperienceService;
    @Autowired
    private SysUserCertificateService userCertificateService;
    @Autowired
    private SysUserEducationService userEducationService;
    @Autowired
    private SysUserFamilyService userFamilyService;
    @Autowired
    private SysUserWorkExperienceController userWorkExperienceController;
    @Autowired
    private SysUserStudyHistoryService userStudyHistoryService;

    @Autowired
    ProjectNoticeServie projectNoticeServie;

    @Autowired
    ProjectPlaceService projectPlaceService;

    @GetMapping(value = "index")
    public String index(Model model, HttpServletRequest request, String userId) {
        String id = CommonUtil.getUserId();
        if (StringUtils.isNotBlank(userId)) {
            id = userId;
            model.addAttribute("shenhe", "1");
            model.addAttribute("shenheinguserid", id);
        }
        SysUserDTO user = userService.selectUserById(id);
        if(user==null){
            // 跳转到登陆页面
            request.setAttribute("type","login");
            return "/login";
        }

        SupervisorFile supervisorFile = new SupervisorFile();
        supervisorFile.setProjectId(user.getId());
        //supervisorFile.setType("101");
        supervisorFile = supervisorFileService.getPersonalImg(user.getId());

        if (StringUtils.isNotBlank(user.getYwType())) {
            userService.selectUserYwTypeName(user);
        }
        //  通过
        request.setAttribute("user", user);
        request.setAttribute("file", supervisorFile);
        List<BaseDict> dwlist = baseDictService.selectByTypeCode("DW001");
        // 学历类型
        List<BaseDict> edulist = baseDictService.selectByTypeCode(DictTypes.EDUCATION.getType());
        //所属行业:
        List<BaseDict> areaList = baseDictService.selectByTypeCode(DictTypes.INDUSTRY.getType());
        // 省
        List<SysRegion> provincelist = sysRegionService.selectListByLevelId("1");
        List<SysRegion> citylist = new ArrayList<SysRegion>();
        // 市
        if (StringUtils.isNotBlank(user.getProvince())) {
            SysRegion provinceSr = new SysRegion();
            provinceSr.setCode(user.getProvince());
            SysRegion province = sysRegionService.selectOne(provinceSr);
            SysRegion citySr = new SysRegion();
            citySr.setParentId(province.getId());
            citylist = sysRegionService.select(citySr);
        } else {
            citylist = sysRegionService.selectListByLevelId("2");
        }
        List<SysRegion> countylist = new ArrayList<SysRegion>();
        // 区
        if (StringUtils.isNotBlank(user.getCity())) {
            SysRegion provinceSr = new SysRegion();
            provinceSr.setCode(user.getCity());
            SysRegion province = sysRegionService.selectOne(provinceSr);
            SysRegion citySr = new SysRegion();
            citySr.setParentId(province.getId());
            countylist = sysRegionService.select(citySr);
        } else {
            countylist = sysRegionService.selectListByLevelId("2");
        }
        //负责地区
        ProjectPlaceDTO pacedto = new ProjectPlaceDTO();
        pacedto.setSupProjectId(user.getId());
        pacedto.setType("003");
        List<ProjectPlaceDTO> listpalce = projectPlaceService.selectPlace(pacedto);
        model.addAttribute("placeList", listpalce);
        for (int i = 0; i < listpalce.size(); i++) {
            String province = listpalce.get(i).getProvince();
            List<SysRegion> citylist1 = sysRegionService.selectSysRegionByParentCode(province);
            listpalce.get(i).setCitys(citylist1);
            String city = listpalce.get(i).getCity();
            List<SysRegion> countylist2 = sysRegionService.selectSysRegionByParentCode(city);
            listpalce.get(i).setCountys(countylist2);
        }
        //部门
        BaseDict deptDict = new BaseDict();
        deptDict.setBadtTypecode(DictTypes.DEPT.getType());
        List<BaseDict> deptList = baseDictService.select(deptDict);
        model.addAttribute("deptList", deptList);
        model.addAttribute("dwlist", dwlist);
        model.addAttribute("edulist", edulist);// 学历
        model.addAttribute("provincelist", provincelist);
        model.addAttribute("citylist", citylist);
        model.addAttribute("countylist", countylist);
        model.addAttribute("areaList", areaList);
        //项目中的角色:
        List<BaseDict> xmjsList = baseDictService.selectByTypeCode(DictTypes.LSXMJS.getType());
        model.addAttribute("xmjsList", xmjsList);
        String GxType = user.getGxType();
        String source = user.getSource();
        //001 正中的    002项目注册生成的    003自行注册的
        String page = "";
        if ("001".equals(source)) {
            //正中个人
            //获取公司列表
            getCompany(model);
            //设置工作经历，项目经历
            getUserWorkExperience(id, model);
            //擅长领域
            getDoBest(user, model);
            //证书名称列表：
            List<BaseDict> certNameList = baseDictService.selectByTypeCode(DictTypes.ZSMC.getType());
            //证书级别列表：
            List<BaseDict> certLevelList = baseDictService.selectByTypeCode(DictTypes.ZSJB.getType());
            model.addAttribute("certNameList", certNameList);
            model.addAttribute("certLevelList", certLevelList);
            //获取用户资质证明
            getUserCert(id, model);
            //民族：
            List<BaseDict> nationList = baseDictService.selectByTypeCode(DictTypes.NATION.getType());
            model.addAttribute("nationList", nationList);
            //婚育：
            List<BaseDict> maritalStatusList = baseDictService.selectByTypeCode(DictTypes.MARISTATUS.getType());
            model.addAttribute("maritalStatusList", maritalStatusList);
            //政治面貌：
            List<BaseDict> politicalList = baseDictService.selectByTypeCode(DictTypes.POLITIC.getType());
            model.addAttribute("politicalList", politicalList);
            //血型：
            List<BaseDict> bloodTypeList = baseDictService.selectByTypeCode(DictTypes.BLOODTYPE.getType());
            model.addAttribute("bloodTypeList", bloodTypeList);
            //星座：
            List<BaseDict> constellationList = baseDictService.selectByTypeCode(DictTypes.CONSTELLATION.getType());
            model.addAttribute("constellationList", constellationList);
            //属相
            List<BaseDict> zodiacList = baseDictService.selectByTypeCode(DictTypes.ZODIAC.getType());
            model.addAttribute("zodiacList", zodiacList);
            //岗位职称：
            List<BaseDict> gwzcList = baseDictService.selectByTypeCode(DictTypes.GWZC.getType());
            model.addAttribute("gwzcList", gwzcList);
            //第一学历  最终学历
            getUserEdu(id, model);
            //家庭成员信息：
            getUserFamily(id, model);
            //用户当前工作状况：
            getUserWorkNow(id, model);
            return "/personcenter/indexGFGR_zz";
        } else if ("003".equals(source)) {
            if (StringUtils.isBlank(GxType)) {
                model.addAttribute("message", "请先设置账号供需类型");
                return "/error/error";
            }
            if (StringUtils.isBlank(user.getPersonType())) {
                model.addAttribute("message", "请先设置账号(个人/组织)属性");
                return "/error/error";
            }
            //个人注册的:
            if ("002".equals(GxType)) {
                // 需方
                return "/personcenter/indexXf";
            } else if ("001".equals(GxType)) {
                //供方
                String PersonType = user.getPersonType();
                if ("001".equals(PersonType)) {
                    //  供方-- 个人
                    //获取公司列表
                    getCompany(model);
                    //设置工作经历，项目经历
                    getUserWorkExperience(id, model);
                    //擅长领域
                    getDoBest(user, model);
                    //证书名称列表：
                    List<BaseDict> certNameList = baseDictService.selectByTypeCode(DictTypes.ZSMC.getType());
                    //证书级别列表：
                    List<BaseDict> certLevelList = baseDictService.selectByTypeCode(DictTypes.ZSJB.getType());
                    model.addAttribute("certNameList", certNameList);
                    model.addAttribute("certLevelList", certLevelList);
                    //获取用户资质证明
                    getUserCert(id, model);
                    return "/personcenter/indexGFGR";
                } else if ("002".equals(PersonType)) {
                    //  供方-- 组织
                    //查询供方组织的承诺函:
                    SupervisorFile cnh = new SupervisorFile();
                    cnh.setType("552");
                    cnh.setProjectId(id);
                    List<SupervisorFile> cnhList = supervisorFileService.select(cnh);
                    if (cnhList.size() > 0) {
                        SupervisorFile cnhFile = cnhList.get(0);
                        if (StringUtils.isNotBlank(cnhFile.getUrl())) {
                            String newUrl = File.separator + "userfile" + cnhFile.getUrl().substring((uploadUtil.getUploadPath() + uploadUtil.getUserPath()).length());
                            cnhFile.setUrl(newUrl);
                        }
                        model.addAttribute("cnh", cnhFile);
                    }
                    return "/personcenter/indexGFZZ";
                }
            }
        } else if ("002".equals(source)) {
            //项目创建时创建的账号:
            if ("002".equals(GxType)) {
                //项目创建的业主单位:
                return "/personcenter/indexXf_YZ";
            }
            if (StringUtils.isBlank(GxType)) {
                //没有供需的是项目创建的承建单位:
                return "/personcenter/index_CJ";
            }
            //供方
            String PersonType = user.getPersonType();
            if ("001".equals(PersonType)) {
                //  供方-- 个人
                //获取公司列表
                getCompany(model);
                //设置工作经历，项目经历
                getUserWorkExperience(id, model);
                //擅长领域
                getDoBest(user, model);
                //证书名称列表：
                List<BaseDict> certNameList = baseDictService.selectByTypeCode(DictTypes.ZSMC.getType());
                //证书级别列表：
                List<BaseDict> certLevelList = baseDictService.selectByTypeCode(DictTypes.ZSJB.getType());
                model.addAttribute("certNameList", certNameList);
                model.addAttribute("certLevelList", certLevelList);
                //获取用户资质证明
                getUserCert(id, model);
                return "/personcenter/indexGFGR";
            }
        } else {
            if (StringUtils.isBlank(source)) {
                model.addAttribute("message", "请先设置账号来源");
                return "/error/error";
            }
        }

        return "/error/error";
    }

    private void getCompany(Model model) {
        Example example = new Example(BaseCompany.class);
        example.setOrderByClause("bc_create_time desc");
        List<BaseCompany> companyList = companyService.selectByExample(example);
        model.addAttribute("companyList", companyList);
    }

    private void getDoBest(SysUserDTO user, Model model) {
        //擅长领域：
        List<BaseDict> doBestList = baseDictService.selectByTypeCode(DictTypes.DOBEST.getType());
        if (StringUtils.isNotBlank(user.getDoBest())) {
            getDoBestAlready(doBestList, user);
        }
        model.addAttribute("doBestList", doBestList);
    }


    /**
     * 获取用户的学历
     *
     * @param userId
     * @param model
     */
    private void getUserEdu(String userId, Model model) {
        //获取用户的第一学历：
        SysUserEducation firstEducation = new SysUserEducation();
        firstEducation.setSuId(userId);
        List<SysUserEducation> userEducationList = userEducationService.select(firstEducation);
        if (userEducationList != null && userEducationList.size() > 0) {
            for (SysUserEducation education : userEducationList) {
                String userEducationType = education.getSuenType();
                if (StringUtils.isNotBlank(userEducationType)) {
                    //查找文件:
                    SupervisorFile file = new SupervisorFile();
                    file.setLinkId(education.getSuenId());
                    List<SupervisorFile> educationFileList = supervisorFileService.select(file);
                    if (educationFileList != null && educationFileList.size() > 0) {
                        for (SupervisorFile eduFile : educationFileList) {
                            if ("555".equals(eduFile.getType())) {
                                //第一学历学历证明
                                education.setSuenCertFile(eduFile.getUrl());
                            } else if ("556".equals(eduFile.getType())) {
                                education.setSuenXuexinFile(eduFile.getUrl());
                            }
                        }
                    }
                    if ("first".equals(userEducationType)) {
                        model.addAttribute("firstEducation", education);
                    } else if ("last".equals(userEducationType)) {
                        model.addAttribute("lastEducation", education);
                    }
                }
            }
        }
    }

    /**
     * 获取用户的家庭信息
     *
     * @param userId
     * @param model
     */
    private void getUserFamily(String userId, Model model) {
        if (StringUtils.isNotBlank(userId)) {
            //配偶：
            SysUserFamily spouse = new SysUserFamily();
            spouse.setSuId(userId);
            spouse.setSufRelationship("3");
            List<SysUserFamily> spouseList = userFamilyService.select(spouse);
            if (spouseList != null && spouseList.size() > 0) {
                model.addAttribute("spouse", spouseList.get(0));
            }
            //子女：
            Example childExample = new Example(SysUserFamily.class);
            Example.Criteria criteria = childExample.createCriteria();
            criteria.andEqualTo("suId", userId);
            Example.Criteria criteria1 = childExample.createCriteria();
            criteria1.setAndOr("and");
            criteria1.orEqualTo("sufRelationship", "4");
            criteria1.orEqualTo("sufRelationship", "5");
            childExample.setOrderByClause("ind asc");
            childExample.and(criteria1);
            List<SysUserFamily> childList = userFamilyService.selectByExample(childExample);
            if (childList != null && childList.size() > 0) {
                model.addAttribute("childList", JSONObject.toJSONString(childList));
            }
        }
    }

    /**
     * 获取用户当前工作状态
     *
     * @param userId
     * @param model
     */
    private void getUserWorkNow(String userId, Model model) {
        if (StringUtils.isNotBlank(userId)) {
            SysUserWorkExperience sysUserWorkExperience = new SysUserWorkExperience();
            sysUserWorkExperience.setSuId(userId);
            sysUserWorkExperience.setIfNow("1");
            List<SysUserWorkExperience> select = sysUserWorkExperienceService.select(sysUserWorkExperience);
            if (select != null && select.size() > 0) {
                model.addAttribute("nowWork", select.get(0));
            }
        }
    }

    /**
     * 获取用户资质证明列表
     *
     * @return
     */
    @RequestMapping("/selectCertList")
    @ResponseBody
    public JsonUtil getUserCertList(String userId, String abc) {
        JsonUtil jsonUtil = new JsonUtil();
        if (StringUtils.isBlank(userId)) {
            userId = CommonUtil.getUserId();
        }
        List<SysUserCertificate> userCertList = getUserCertList(userId);
        jsonUtil.setFlag(true);
        jsonUtil.setData(userCertList);
        return jsonUtil;
    }

    /*
     * 审核用户
     * @return
     */
    @RequestMapping(value = "/audit", method = RequestMethod.POST)
    @ResponseBody
    public JsonUtil audit(SysUser user) {
        if (user == null || StringUtils.isBlank(user.getId()) || StringUtils.isBlank(user.getAuditStatus())) {
            return JsonUtil.error("参数异常");
        }
        SysUser userInfo = userService.selectByPrimaryKey(user.getId());

        if ("1".equals(user.getAuditStatus()) && StringUtils.isNotBlank(userInfo.getGxType())
                && StringUtils.isNotBlank(userInfo.getPersonType()) && "002".equals(user.getSource())) {
            user.setSource("003");
        }
        String auditStatus = user.getAuditStatus();
        sendZhNoticeCheck(user, auditStatus);
        userService.updateByPrimaryKeySelective(user);
        return JsonUtil.sucess("操作成功");
    }


    public void sendZhNoticeCheck(SysUser user, String auditStatus) {
        ProjectNotice notice = new ProjectNotice();
        notice.setLinkId(user.getId());
        notice.setIsView("0");
        notice.setSendTo(user.getId());
        if ("1".equals(auditStatus)) {
            notice.setTitle("您的个人信息审核通过");
        } else {
            notice.setTitle("您的个人信息审核不通过");
        }
        notice.setNoticeType("111");//通知类型 账号通知 001  002 流程进展通知
        notice.setApplicantType("");// 监理
        projectNoticeServie.insertSelective(notice);
    }

    @ResponseBody
    @RequestMapping("/getAuditStatus")
    public JsonUtil getAuditStatus(SysUser user) {
        JsonUtil result = new JsonUtil();
        if (user != null || StringUtils.isNotBlank(user.getId())) {
            SysUser sysUser = userService.selectByPrimaryKey(user.getId());
            if (sysUser != null && StringUtils.isNotBlank(sysUser.getAuditStatus())) {
                result.setFlag(true);
                result.setData(sysUser.getAuditStatus());
                if ("2".equals(sysUser.getAuditStatus())) {
                    result.setMsg(sysUser.getAuditFailReason());
                }
            }
        } else {
            result.setFlag(false);
            result.setMsg("参数错误");
        }
        return result;
    }

    /*
     * 获取用户业绩列表及证明文件
     *
     * @return
     */
    @RequestMapping("/selectYjList")
    @ResponseBody
    public JsonUtil getUserYjList(String userId, String abc) {
        JsonUtil jsonUtil = new JsonUtil();
        if (StringUtils.isBlank(userId)) {
            userId = CommonUtil.getUserId();
        }
        List<SysUserProject> userProjectList = getUserYjList(userId);
        jsonUtil.setFlag(true);
        jsonUtil.setData(userProjectList);
        return jsonUtil;
    }

    private void getUserCert(String id, Model model) {
        //用户资质证明
        List<SysUserCertificate> sysUserCertificates = getUserCertList(id);
        if (sysUserCertificates != null && sysUserCertificates.size() == 0) {
            SysUserCertificate empty = new SysUserCertificate();
            empty.setSucId(IdUtil.simpleUUID());
            empty.setSuId(id);
            sysUserCertificates.add(empty);
        }
        if (sysUserCertificates != null && sysUserCertificates.size() > 0) {
            model.addAttribute("userCertList", sysUserCertificates);
        }
    }

    private List<SysUserCertificate> getUserCertList(String id) {
        List<SysUserCertificate> sysUserCertificates = new ArrayList<>();
        if (StringUtils.isNotBlank(id)) {
            SysUserCertificate userCertificate = new SysUserCertificate();
            userCertificate.setSuId(id);
            sysUserCertificates = userCertificateService.selectUserCert(userCertificate);
        }
        return sysUserCertificates;
    }

    private List<SysUserProject> getUserYjList(String id) {
        List<SysUserProject> userProjectList = new ArrayList<>();
        if (StringUtils.isNotBlank(id)) {
            SysUserProject userProject = new SysUserProject();
            userProject.setSuId(id);
            userProjectList = sysUserProjectService.selectUserYj(userProject);
        }
        return userProjectList;
    }

    private void getUserWorkExperience(String id, Model model) {
        //工作经历/项目经历
        Example workExperienceExample = new Example(SysUserWorkExperience.class);
        Example.Criteria criteria = workExperienceExample.createCriteria();
        criteria.andEqualTo("suId", id);
        Example.Criteria criteria1 = workExperienceExample.createCriteria();
        criteria1.andIsNull("ifNow");
        criteria1.orEqualTo("ifNow", "");
        criteria1.orNotEqualTo("ifNow", "1");
        workExperienceExample.and(criteria1);
        workExperienceExample.setOrderByClause("suw_ind asc");
        List<SysUserWorkExperience> workExperienceList = sysUserWorkExperienceService.selectByExample(workExperienceExample);
        if (workExperienceList != null && workExperienceList.size() > 0) {
            for (SysUserWorkExperience experience : workExperienceList) {
                Example userProjectExample = new Example(SysUserProject.class);
                userProjectExample.and().andEqualTo("suweId", experience.getSuweId());
                userProjectExample.setOrderByClause("table_ind asc");
                List<SysUserProject> userProjectList = sysUserProjectService.selectByExample(userProjectExample);
                experience.setUserProjectList(userProjectList);
            }
            model.addAttribute("workList", JSONObject.toJSONString(workExperienceList));
        }
    }

    private void getDoBestAlready(List<BaseDict> doBestList, SysUserDTO user) {
        if (doBestList.size() > 0 && StringUtils.isNotBlank(user.getDoBest())) {
            String[] userDoBestArray = user.getDoBest().split(",");
            List<String> userDoBestList = Arrays.nonNullElementsIn(userDoBestArray);
            for (BaseDict baseDict : doBestList) {
                if (userDoBestList.contains(baseDict.getBadtCode())) {
                    baseDict.setBadtNote("1");
                }
            }
        }
    }

    @ApiOperation(value = "/updateUsers", httpMethod = "POST", notes = "完善用户")
    @Log(desc = "完善用户", type = Log.LOG_TYPE.UPDATE)
    @PostMapping(value = "updateUsers")
    @ResponseBody
    public JsonUtil updateUsers(SysUser sysUser) {
        JsonUtil jsonUtil = new JsonUtil();
        jsonUtil.setFlag(false);
        if (sysUser == null) {
            jsonUtil.setMsg("获取数据失败");
            return jsonUtil;
        }
        try {
            if (StringUtils.isNotBlank(sysUser.getPhoneNumber())) {
                JsonUtil jsonUtil1 = userService.checkSameTelephoneWhenUpdate(sysUser);
                if (!jsonUtil1.isFlag()) {
                    return jsonUtil1;
                }
            }
            if (StringUtils.isNotBlank(sysUser.getEmail())) {
                JsonUtil jsonUtil2 = userService.checkSameEmailWhenUpdate(sysUser);
                if (!jsonUtil2.isFlag()) {
                    return jsonUtil2;
                }
            }
            ArrayList<SysUserEducation> educations = sysUser.getEducations();
            if (educations != null && educations.size() > 0) {
                updateUserEducation(sysUser);
            }
            ArrayList<SysUserFamily> families = sysUser.getFamilys();
            if (families != null && families.size() > 0) {
                updateUserFamily(sysUser);
            }
            SysUserWorkExperience nowWork = sysUser.getNowWork();
            if (nowWork != null) {
                updateUserNowWork(sysUser);
            }
            //负责地区
            ArrayList<ProjectPlace> places = sysUser.getProjectPlacedtos();
            if (places != null && places.size() > 0) {
                updateUserPlacedtos(places, sysUser.getId());
            }
            sysUser.setAuditStatus("3");
            userService.updateByPrimaryKeySelective(sysUser);

            if (StringUtils.isNotBlank(sysUser.getWorkExJson())) {
                ArrayList<SysUserWorkExperience> sysUserWorkExperiences = (ArrayList) JSONArray.parseArray(sysUser.getWorkExJson(), SysUserWorkExperience.class);
                if (sysUserWorkExperiences != null && sysUserWorkExperiences.size() > 0) {
                    userWorkExperienceController.saveWorkExperience(sysUserWorkExperiences);
                }
            }
            // 给管理员发送消息 提醒
            sendNoticeCheckToAdmin(sysUser);


        } catch (MyException e) {
            e.printStackTrace();
            jsonUtil.setFlag(false);
            jsonUtil.setMsg("操作失败");
            return jsonUtil;
        }
        jsonUtil.setFlag(true);
        jsonUtil.setMsg("操作成功");
        return jsonUtil;
    }

    public void sendNoticeCheckToAdmin(SysUser user) {
        SysUser adminuser = new SysUser();
        adminuser.setUsername("admin");
        List<SysUser> select = userService.select(adminuser);
        if (select != null) {
            if (select.size() > 0) {
                SysUser sysUser = select.get(0);
                String touserid = sysUser.getId();
                ProjectNotice notice = new ProjectNotice();
                notice.setLinkId(user.getId());
                notice.setIsView("0");
                notice.setSendTo(touserid);
                notice.setTitle("账号" + user.getUsername() + "的个人信息需要审核");
                notice.setNoticeType("113");//通知类型 账号通知 001  002 流程进展通知
                notice.setApplicantType("000");// 系统
                projectNoticeServie.insertSelective(notice);
            }


        }


    }

    private void updateUserEducation(SysUser sysUser) {
        ArrayList<SysUserEducation> userEducations = sysUser.getEducations();
        if (userEducations != null && userEducations.size() > 0) {
            for (SysUserEducation education : userEducations) {
                if (StringUtils.isBlank(education.getSuenId())) {
                    //新增:
                    education.setSuId(sysUser.getId());
                    education.setSuenId(null);
                    userEducationService.insertSelective(education);
                } else {
                    SysUserEducation dbEdu = userEducationService.selectByPrimaryKey(education);
                    if (dbEdu != null) {
                        //更改:
                        userEducationService.updateByPrimaryKeySelective(education);
                    } else {
                        education.setSuId(sysUser.getId());
                        userEducationService.insertSelective(education);
                    }

                }
            }
        }
    }

    private void updateUserFamily(SysUser sysUser) {
        ArrayList<SysUserFamily> families = sysUser.getFamilys();
        if (families != null && families.size() > 0) {
            for (SysUserFamily family : families) {
                if (StringUtils.isBlank(family.getSufId())) {

                    if ("3".equals(family.getSufRelationship())) {
                        //如果是配偶，查询一遍
                        SysUserFamily dbFamily = new SysUserFamily();
                        dbFamily.setSuId(sysUser.getId());
                        dbFamily.setSufRelationship(family.getSufRelationship());
                        List<SysUserFamily> select = userFamilyService.select(dbFamily);
                        if (select != null && select.size() > 0) {
                            family.setSufId(select.get(0).getSufId());
                            userFamilyService.updateByPrimaryKeySelective(family);
                            return;
                        }
                    }

                    family.setSufId(null);
                    family.setSuId(sysUser.getId());
                    family.setCreateTime(DateUtil.getCurrentDateTimeString());
                    family.setCreateBy(sysUser.getId());
                    userFamilyService.insertSelective(family);
                } else {
                    userFamilyService.updateByPrimaryKeySelective(family);
                }
            }
        }
    }

    private void updateUserNowWork(SysUser sysUser) {
        if (sysUser.getNowWork() != null) {
            SysUserWorkExperience nowWork = sysUser.getNowWork();
            if (StringUtils.isBlank(nowWork.getSuweId())) {
                //看看数据库有没有：
                SysUserWorkExperience dbWorkExperience = new SysUserWorkExperience();
                dbWorkExperience.setSuId(sysUser.getId());
                dbWorkExperience.setIfNow("1");
                List<SysUserWorkExperience> select = sysUserWorkExperienceService.select(dbWorkExperience);
                if (select != null && select.size() > 0) {
                    nowWork.setSuweId(select.get(0).getSuweId());
                    sysUserWorkExperienceService.updateByPrimaryKeySelective(nowWork);
                    return;
                }
                nowWork.setSuweId(null);
                nowWork.setSuId(sysUser.getId());
                sysUserWorkExperienceService.insertSelective(nowWork);
            } else {
                sysUserWorkExperienceService.updateByPrimaryKeySelective(nowWork);
            }
        }
    }

    //负责地区
    private void updateUserPlacedtos(ArrayList<ProjectPlace> place, String userId) {
        if (place != null && place.size() > 0) {
            ProjectPlace place1 = new ProjectPlace();
            place1.setSupProjectId(userId);
            place1.setType("003");
            if (projectPlaceService.delete(place1) >= 0) {
                for (ProjectPlace projectPlace : place) {
                    projectPlace.setProPlaceId(IdUtil.simpleUUID());
                    projectPlace.setType("003");
                    projectPlace.setProvince(projectPlace.getProvince());
                    projectPlace.setSupProjectId(userId);
                    projectPlace.setCity(projectPlace.getCity());
                    projectPlace.setCreateBy(userId);
                    projectPlace.setCreateDate(DateUtil.getCurrentDateTimeString());
                    projectPlaceService.insertSelective(projectPlace);
                }
            }
        }
    }

    @ApiOperation(value = "/getCity", httpMethod = "GET", notes = "注册")
    @GetMapping(value = "getCity")
    @ResponseBody
    public List<SysRegion> getCity(String code) {
        SysRegion sy = new SysRegion();
        sy.setCode(code);
        List<SysRegion> list = sysRegionService.select(sy);
        SysRegion re = list.get(0);
        Long id = re.getId();
        List<SysRegion> ListRe = sysRegionService.selectListByParentId(id);
        return ListRe;
    }

    /**
     * 修改密码
     *
     * @param id
     * @param pass
     * @param newPwd
     * @return
     */
    @Log(desc = "修改密码", type = Log.LOG_TYPE.UPDATE)
    @PostMapping(value = "rePass")
    @ResponseBody
    public JsonUtil rePass(String id, String pass, String newPwd) {
        boolean flag = StringUtils.isEmpty(id) || StringUtils.isEmpty(pass) || StringUtils.isEmpty(newPwd);
        JsonUtil j = new JsonUtil();
        j.setFlag(false);
        if (flag) {
            j.setMsg("获取数据失败，修改失败");
            return j;
        }
        SysUser user = userService.selectByPrimaryKey(id);
        newPwd = Md5Util.getMD5(newPwd, user.getUsername());
        pass = Md5Util.getMD5(pass, user.getUsername());
        if (!pass.equals(user.getPassword())) {
            j.setMsg("密码不正确");
            return j;
        }
        if (newPwd.equals(user.getPassword())) {
            j.setMsg("新密码不能与旧密码相同");

            return j;
        }
        user.setPassword(newPwd);
        try {
            userService.rePass(user);
            j.setMsg("修改成功");
            j.setFlag(true);
        } catch (MyException e) {
            e.printStackTrace();
        }
        return j;
    }

    @ApiOperation(value = "/updateNum", httpMethod = "POST", notes = "标签个数")
    @Log(desc = "标签个数", type = Log.LOG_TYPE.UPDATE)
    @PostMapping(value = "updateNum")
    @ResponseBody
    public JsonUtil updateNum(SysUser sysUser) {
        JsonUtil jsonUtil = new JsonUtil();
        jsonUtil.setFlag(false);
        if (sysUser == null) {
            jsonUtil.setMsg("获取数据失败");
            return jsonUtil;
        }
        try {
            userService.updateNum(sysUser);
        } catch (MyException e) {
            e.printStackTrace();
            jsonUtil.setFlag(false);
            jsonUtil.setMsg("操作失败");
            return jsonUtil;
        }
        jsonUtil.setFlag(true);
        jsonUtil.setMsg("操作成功");
        return jsonUtil;
    }

    @RequestMapping(value = "/uploadFile", method = RequestMethod.POST)
    @ResponseBody
    public JsonUtil addFile(@RequestParam(value = "file", required = false) MultipartFile filedata, SupervisorProjectDTO dto) {
        // 当前用户信息
        String AsUserId = "";
        if (StringUtils.isBlank(dto.getUserId())) {
            AsUserId = CommonUtil.getUserId();
        }
        if (StringUtils.isBlank(AsUserId)) {
            return JsonUtil.error("获取用户信息出错");
        }
        SysUser sysUser = userService.selectByPrimaryKey(AsUserId);
        String AsType = dto.getType();

        JsonUtil re = new JsonUtil();
        try {
            //如果是头像/电子签章/电子签名:
            //判断用户是否有创建好的文件夹,如果有创建好的文件夹,新方式存储,如果没有创建好的文件夹,老方式存储:
            LoadType userLoadType = new LoadType();
//            if (("208".equals(AsType) || "202".equals(AsType) || "203".equals(AsType)) && StringUtils.isBlank(sysUser.getInfoDic())) {
//                //头像图片:
//                userLoadType = uploadUtil.upload(filedata, UploadType.PERSON);
//
//
//
//            } else {
            if (StringUtils.isBlank(sysUser.getInfoDic())) {
                //创建用户目录：
                userService.setUserFilePath(sysUser);
//                        return JsonUtil.error("获取人员资质库目录失败!");
            }
            userLoadType = getLoadTypeByUser(AsType, sysUser, filedata);
            //删除不同后缀的同类文件
            delOldFile(AsType, userLoadType, sysUser);
//            }

            //保存文件
            FileUtils.copyInputStreamToFile(filedata.getInputStream(), userLoadType.getCurrentFile());
            //保存文件表
            SupervisorFile AoPostSf = new SupervisorFile();
            //用户id
            AoPostSf.setProjectId(AsUserId);
            //文件类型
            AoPostSf.setType(AsType);
            //551为资质证明图片类型,dto.getIds为资质证明id:如果传过来了资质证明id,说明是更新的,如果没有资质证明id,那么新建一个id,到时候保存的时候会用这个id
            //553为业绩证明图片类型,553借用certId字段
            //555正中供方个人中心学历证明  556正中供方个人中心学信网图片  借用certId字段
            String certId = "";
            if ("551".equals(AsType) || "553".equals(AsType)
                    || "555".equals(AsType) || "556".equals(AsType)
                    || "557".equals(AsType) || "558".equals(AsType)) {
                certId = StringUtils.isBlank(dto.getIds()) ? IdUtil.simpleUUID() : dto.getIds();
                AoPostSf.setLinkId(certId);
            }
            SupervisorFile supervisorFile = supervisorFileService.selectOne(AoPostSf);
            AoPostSf.setFileName(userLoadType.getFileName());
            AoPostSf.setFileType(userLoadType.getSuffix());
            AoPostSf.setType(dto.getType());
            AoPostSf.setCreateBy(AsUserId);
            AoPostSf.setCreateDate(new Date());
            String fileUrl = "";
//                if(!"208".equals(AsType) ){
//                    String currFilePath = userLoadType.getFilePath();
//                    String userInfoDic = sysUser.getInfoDic();
//                    fileUrl = currFilePath.substring(currFilePath.indexOf(userInfoDic));
//                    AoPostSf.setUrl(fileUrl);
//                }else{
//                    File currentFile = userLoadType.getCurrentFile();
//                    String fileFullPath = currentFile.getPath();
//                    if(StringUtils.isBlank(sysUser.getInfoDic())){
//                        fileUrl = fileFullPath.substring(fileFullPath.indexOf(uploadUtil.getPersonPath())+uploadUtil.getPersonPath().length());
//                    }else{
//                        fileUrl = fileFullPath.substring(fileFullPath.indexOf(uploadUtil.getUserPath())+uploadUtil.getUserPath().length());
//                    }
//                    AoPostSf.setUrl(fileUrl);
//                }

//                if("551".equals(AsType) || "553".equals(AsType)
//                        || "555".equals(AsType)  || "556".equals(AsType)
//                        || "557".equals(AsType)  || "558".equals(AsType)){
//                    AoPostSf.setUrl(fileUrl);
//                }
            //设置AoPostSf的url 为文件的全路径
            AoPostSf.setUrl(userLoadType.getCurrentFile().getPath());
            //增加/更改supervisor_file表
            if (isNull(supervisorFile)) {
                supervisorFileService.insert(AoPostSf);
                supervisorFileService.setFilePathDics(AoPostSf);
            } else {
                AoPostSf.setId(supervisorFile.getId());
                if ("552".equals(AsType) && "2".equals(supervisorFile.getLcStatus())) {
                    re.setStatus(Integer.valueOf(supervisorFile.getLcStatus()));
                }
                supervisorFileService.updateByPrimaryKey(AoPostSf);
            }
            if (AsType.equals("201")) {
                //获取营业执照组织代码证编号
                String accessToken = AuthService.getAuth();
                String result = BusinessLicense.businessLicense(userLoadType.getFilePath(), accessToken);
                JSONObject jsonObject = JSONObject.parseObject(result);
                re.setJosnObj(jsonObject);
            }
            if ("551".equals(AsType) || "553".equals(AsType)
                    || "555".equals(AsType) || "556".equals(AsType)
                    || "557".equals(AsType) || "558".equals(AsType)) {
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("certId", certId);
                re.setJosnObj(jsonObject);
            }
            if ("552".equals(AsType)) {
                re.setMsg(AoPostSf.getId());
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("suffix", filedata.getOriginalFilename().substring(filedata.getOriginalFilename().lastIndexOf(".") + 1));
                jsonObject.put("fileurl", File.separator + "userfile" + (AoPostSf.getUrl().substring((uploadUtil.getUploadPath() + uploadUtil.getUserPath()).length())));
                re.setJosnObj(jsonObject);
            } else {
                re.setMsg(userLoadType.getOriginalFileName());
            }
            //返回值data带着图片的路径
            //前半截:   截取掉uploadPath    如果是以 userPath开头  则为 /userfile    如果是以 personalPath开头则为 /images
            //后半截:    如果用户的info_dic为空  则为图片名称     如果用户的info_dic不为空  则为用户的info_dic+图片名称
            String filePathBack = userLoadType.getFilePath().substring(uploadUtil.getUploadPath().length());
            if (filePathBack.startsWith(uploadUtil.getPersonPath())) {
                fileUrl = File.separator + "images" + File.separator + userLoadType.getFileName();
            } else if (filePathBack.startsWith(uploadUtil.getUserPath())) {
                fileUrl = File.separator + "userfile" + File.separator + filePathBack.substring(uploadUtil.getUserPath().length());
            } else {
                throw new RuntimeException("图片路径错误");
            }
            re.setData(fileUrl);
            if ("202".equals(AsType) || "203".equals(AsType)) {
                //处理图片背景透明度
                ImageUtil.transparentBackground(userLoadType.getCurrentFile().getPath(), "png", userLoadType.getCurrentFile().getPath());
            }
        } catch (Exception e) {
            re.setMsg(e.getMessage());
            re.setFlag(false);
            e.printStackTrace();
        }
        return re;
    }


    private void delOldFile(String asType, LoadType userLoadType, SysUser user) {
        //几种不删除的情况:
        if ("999".equals(asType)) {
            return;
        }
        String fileName = userLoadType.getFileName();
        String delFileSame = fileName.substring(0, fileName.lastIndexOf(".") + 1);
        String userDic = "";
        if (StringUtils.isBlank(user.getInfoDic())) {
            userDic = uploadUtil.getUploadPath() + uploadUtil.getPersonPath();
        } else {
            userDic = uploadUtil.getUploadPath() + uploadUtil.getUserPath() + user.getInfoDic();
        }
        File userDicFile = new File(userDic);
        if (userDicFile.exists() && userDicFile.isDirectory()) {
            File[] files = userDicFile.listFiles();
            Iterator<File> iterator = java.util.Arrays.stream(files).iterator();
            iterator.forEachRemaining(file -> {
                if (file.getName().startsWith(delFileSame)) {
                    file.delete();
                }
            });
        }
    }

    @ResponseBody
    @RequestMapping(value = "/addCert", method = RequestMethod.POST)
    public JsonUtil addUserCert(@RequestBody SysUserCertificate certificate) {
        JsonUtil result = new JsonUtil();
        // 当前用户信息
        Subject sub = SecurityUtils.getSubject();
        CurrentUser currentUser = (CurrentUser) sub.getPrincipal();
        String AsUserId = currentUser.getId();

        certificate.setSuId(AsUserId);
        if (StringUtils.isBlank(certificate.getSucId())) {
            //没有上传过图片的新建情况:
            certificate.setCreateTime(DateUtil.getCurrentDateString());
            userCertificateService.insertSelective(certificate);
        } else {
            SysUserCertificate userCertificate = userCertificateService.selectByPrimaryKey(certificate.getSucId());
            if (userCertificate == null) {
                certificate.setCreateTime(DateUtil.getCurrentDateString());
                userCertificateService.insertSelective(certificate);
            } else {
                userCertificateService.updateByPrimaryKeySelective(certificate);
            }
        }
        //更改用户审核状态为待审核
        userService.updateUserAuditStatus(CommonUtil.getUserId(), "3", null);
        result.setFlag(true);
        return result;
    }

    @ResponseBody
    @RequestMapping(value = "/addCerts", method = RequestMethod.POST)
    public JsonUtil addUserCerts(@RequestBody ArrayList<SysUserCertificate> certificateList) {
        JsonUtil result = new JsonUtil();
        // 当前用户信息
        Subject sub = SecurityUtils.getSubject();
        CurrentUser currentUser = (CurrentUser) sub.getPrincipal();
        String AsUserId = currentUser.getId();

        if (certificateList.size() > 0) {
            for (SysUserCertificate certificate : certificateList) {
                certificate.setSuId(AsUserId);
                if (StringUtils.isBlank(certificate.getSucId())) {
                    //没有上传过图片的新建情况:
                    certificate.setCreateTime(DateUtil.getCurrentDateString());
                    userCertificateService.insertSelective(certificate);
                } else {
                    SysUserCertificate userCertificate = userCertificateService.selectByPrimaryKey(certificate.getSucId());
                    if (userCertificate == null) {
                        certificate.setCreateTime(DateUtil.getCurrentDateString());
                        userCertificateService.insertSelective(certificate);
                    } else {
                        userCertificateService.updateByPrimaryKeySelective(certificate);
                    }
                }
            }
        }
        result.setFlag(true);
        return result;
    }

    /**
     * 根据用户获取loadType
     *
     * @param user
     * @return
     */
    @SneakyThrows
    private LoadType getLoadTypeByUser(String fileType, SysUser user, MultipartFile file) {
        if (user == null || file == null || user == null) {
            return null;
        }
        LoadType loadType = new LoadType();
        if (uploadUtil.whehterAllowFileType(file)) {
            //获取文件名称: 把文件原名称  文件后缀   文件新名称存入loadType
            formatUserFileNameByFileType(fileType, file, loadType, user);
            //准备好文件所在文件夹,判断有没有文件,有的话删除原文件,并创建新文件
            getCurrentFilePath(loadType, user);
        } else {
            throw new MyException("抱歉，上传文件不是允许的文件类型！！");
        }
        return loadType;
    }

    /**
     * 编辑真实存储路径
     *
     * @param loadType
     * @param user
     * @throws IOException
     */
    private void getCurrentFilePath(LoadType loadType, SysUser user) throws IOException {
        StringBuffer filePath = new StringBuffer();
        String dicName = "";
        if (StringUtils.isNotBlank(user.getInfoDic())) {
            dicName = uploadUtil.getUserPath();
        } else {
            //存储到personal文件夹下
            dicName = uploadUtil.getPersonPath();
        }

        //拼接用户信息文件存储路径
        filePath.append(uploadUtil.getUploadPath())
                .append(dicName)
                .append(File.separator);

        if (StringUtils.isNotBlank(user.getInfoDic())) {
            filePath.append(user.getInfoDic());
        }
        File fileDic = new File(filePath.toString());
        //如果目录不存在,创建目录
        if (!fileDic.exists() || fileDic.isFile()) {
            fileDic.mkdirs();
        }
        //拼接新文件的全路径
        String currentFileFullName = filePath.append(File.separator).append(loadType.getFileName()).toString();
        File file = new File(FilePathUtil.doFileSeparator(currentFileFullName));
        if (file.exists()) {
            file.delete();
        }
        file.createNewFile();
        loadType.setCurrentFile(file);
    }

    private void formatUserFileNameByFileType(String fileType, MultipartFile file, LoadType loadType, SysUser user) {
        //文件原名称
        String fileFuleName = file.getOriginalFilename();
        //文件后缀   .xxx
        String fileSuffix = fileFuleName.substring(fileFuleName.lastIndexOf("."));
        //获取文件类型对应的文件名称
        String fileNameFront = uploadUtil.getUserFileName(fileType);
        //如果是多图片的类型,拼接后缀:
        if ("551".equals(fileType) || "553".equals(fileType)) {
            //获取文件夹中,有多少个这个类型的图片,然后拼接后缀
            String userInfoDoc = user.getInfoDic();
            String filePath = uploadUtil.getUploadPath() + uploadUtil.getUserPath() + userInfoDoc;
            fileNameFront = uploadUtil.getFileCountByFileName(fileNameFront, filePath);
        }
        //如果没有指定目录,文件名称带上用户名前缀
        if (StringUtils.isBlank(user.getInfoDic())) {
            fileNameFront = user.getRealName() + "_" + fileNameFront;
        }
        //拼接新的文件名称
        String fileName = fileNameFront + fileSuffix;
        loadType.setOriginalFileName(fileFuleName);
        loadType.setFileName(fileName);
        loadType.setSuffix(fileSuffix);
    }

    @ResponseBody
    @RequestMapping(value = "/addCertList", method = RequestMethod.POST)
    public JsonUtil updateUserCertList(@RequestBody ArrayList<SysUserCertificate> certificateList) {
        JsonUtil result = new JsonUtil();
        // 当前用户信息
        Subject sub = SecurityUtils.getSubject();
        CurrentUser currentUser = (CurrentUser) sub.getPrincipal();
        String AsUserId = currentUser.getId();

        try {
            if (certificateList != null && certificateList.size() > 0) {
                for (SysUserCertificate certificate : certificateList) {
                    certificate.setSuId(AsUserId);
                    if (StringUtils.isBlank(certificate.getSucId())) {
                        //没有上传过图片的新建情况:
                        certificate.setCreateTime(DateUtil.getCurrentDateString());
                        userCertificateService.insertSelective(certificate);
                    } else {
                        SysUserCertificate userCertificate = userCertificateService.selectByPrimaryKey(certificate.getSucId());
                        if (userCertificate == null) {
                            certificate.setCreateTime(DateUtil.getCurrentDateString());
                            userCertificateService.insertSelective(certificate);
                        } else {
                            userCertificateService.updateByPrimaryKeySelective(certificate);
                        }
                    }
                }
            }
            //更改用户审核状态为待审核
            userService.updateUserAuditStatus(CommonUtil.getUserId(), "3", null);
            result.setFlag(true);
            return result;
        } catch (Exception e) {
            result.setFlag(false);
            result.setMsg("系统出错");
            e.printStackTrace();
            return result;
        }
    }

    @ResponseBody
    @RequestMapping(value = "/addProjectList", method = RequestMethod.POST)
    public JsonUtil updateUserProjectList(@RequestBody ArrayList<SysUserProject> projectList) {
        JsonUtil result = new JsonUtil();
        // 当前用户信息
        Subject sub = SecurityUtils.getSubject();
        CurrentUser currentUser = (CurrentUser) sub.getPrincipal();
        String AsUserId = currentUser.getId();

        try {
            if (projectList != null && projectList.size() > 0) {
                for (SysUserProject project : projectList) {
                    project.setSuId(AsUserId);
                    if (StringUtils.isBlank(project.getSupId())) {
                        //没有上传过图片的新建情况:
                        project.setCreateDate(DateUtil.getCurrentDateString());
                        sysUserProjectService.insertSelective(project);
                    } else {
                        SysUserProject userProject = sysUserProjectService.selectByPrimaryKey(project.getSupId());
                        if (userProject == null) {
                            project.setCreateDate(DateUtil.getCurrentDateString());
                            sysUserProjectService.insertSelective(project);
                        } else {
                            sysUserProjectService.updateByPrimaryKeySelective(project);
                        }
                    }
                }
            }
            //更改用户审核状态为待审核
            userService.updateUserAuditStatus(CommonUtil.getUserId(), "3", null);
            result.setFlag(true);
            return result;
        } catch (Exception e) {
            result.setFlag(false);
            result.setMsg("系统出错");
            e.printStackTrace();
            return result;
        }
    }

    @ResponseBody
    @RequestMapping(value = "/delCert", method = RequestMethod.POST)
    public JsonUtil delUserCert(SysUserCertificate certificate) {
        JsonUtil result = new JsonUtil();
        // 当前用户信息
        Subject sub = SecurityUtils.getSubject();
        CurrentUser currentUser = (CurrentUser) sub.getPrincipal();
        String AsUserId = currentUser.getId();
        certificate.setSuId(AsUserId);
        try {
            if (StringUtils.isNotBlank(certificate.getSucId())) {
                //删除可能存在的照片:
                SupervisorFile supervisorFile = new SupervisorFile();
                supervisorFile.setLinkId(certificate.getSucId());
                supervisorFile.setType("551");
                supervisorFile.setProjectId(AsUserId);
                supervisorFileService.delete(supervisorFile);
                userCertificateService.deleteByPrimaryKey(certificate);
            }
            result.setFlag(true);
            return result;
        } catch (Exception e) {
            result.setFlag(false);
            result.setMsg("系统出错");
            e.printStackTrace();
            return result;
        }
    }

    @ResponseBody
    @RequestMapping(value = "/delYj", method = RequestMethod.POST)
    public JsonUtil delUserYj(SysUserProject userProject) {
        JsonUtil result = new JsonUtil();
        // 当前用户信息
        Subject sub = SecurityUtils.getSubject();
        CurrentUser currentUser = (CurrentUser) sub.getPrincipal();
        String AsUserId = currentUser.getId();
        userProject.setSuId(AsUserId);
        try {
            if (StringUtils.isNotBlank(userProject.getSupId())) {
                //删除可能存在的照片:
                SupervisorFile supervisorFile = new SupervisorFile();
                supervisorFile.setLinkId(userProject.getSupId());
                supervisorFile.setType("553");
                supervisorFile.setProjectId(AsUserId);
                supervisorFileService.delete(supervisorFile);
                sysUserProjectService.deleteByPrimaryKey(userProject);
            }
            result.setFlag(true);
            return result;
        } catch (Exception e) {
            result.setFlag(false);
            result.setMsg("系统出错");
            e.printStackTrace();
            return result;
        }
    }

    @ResponseBody
    @RequestMapping("/updatecnh")
    public JsonUtil finishcnh(SupervisorFile supervisorFile) {
        if (supervisorFile == null || StringUtils.isBlank(supervisorFile.getId())) {
            return JsonUtil.error("没有文件,无法完成");
        }
        SupervisorFile willFinishFile = new SupervisorFile();
        willFinishFile.setId(supervisorFile.getId());
        willFinishFile.setLcStatus("2");
        supervisorFileService.updateByPrimaryKeySelective(willFinishFile);
        return JsonUtil.sucess("操作成功");
    }

    @ResponseBody
    @RequestMapping("/delcnh")
    public JsonUtil delcnh(SupervisorFile supervisorFile) {
        if (supervisorFile == null || StringUtils.isBlank(supervisorFile.getId())) {
            return JsonUtil.error("没有文件");
        }
        SupervisorFile willFinishFile = new SupervisorFile();
        willFinishFile.setId(supervisorFile.getId());
        supervisorFileService.deleteByPrimaryKey(supervisorFile);
        return JsonUtil.sucess("操作成功");
    }

    @ResponseBody
    @RequestMapping("/delUserFamily")
    public JsonUtil delUserFamily(SysUserFamily family) {
        if (family == null || StringUtils.isBlank(family.getSufId())) {
            return JsonUtil.error("没有需要删除的家庭成员");
        }
        userFamilyService.deleteByPrimaryKey(family);
        return JsonUtil.sucess("操作成功");
    }

    @ResponseBody
    @RequestMapping("/delUserStudy")
    public JsonUtil delUserStudy(SysUserStudyHistory userStudyHistory) {
        if (userStudyHistory != null && StringUtils.isNotBlank(userStudyHistory.getSusId())) {
            userStudyHistoryService.deleteByPrimaryKey(userStudyHistory);
        }
        return JsonUtil.sucess("操作成功");
    }

    @ResponseBody
    @RequestMapping("/saveStudy")
    public JsonUtil saveStudy(@RequestBody ArrayList<SysUserStudyHistory> userStudyList) {
        String userId = CommonUtil.getUserId();
        if (userStudyList.size() > 0) {
            for (SysUserStudyHistory history : userStudyList) {
                String susId = history.getSusId();
                if (StringUtils.isNotBlank(susId)) {
                    SysUserStudyHistory userStudyHistoryDB = userStudyHistoryService.selectByPrimaryKey(susId);
                    if (userStudyHistoryDB == null) {
                        history.setSuId(userId);
                        history.setCreateTime(DateUtil.getCurrentDateTimeString());
                        userStudyHistoryService.insertSelective(history);
                    } else {
                        userStudyHistoryService.updateByPrimaryKeySelective(history);
                    }
                } else {
                    history.setSuId(userId);
                    history.setCreateTime(DateUtil.getCurrentDateTimeString());
                    userStudyHistoryService.insertSelective(history);
                }
                history.setSuId(userId);
            }
        }
        //更改用户审核状态为待审核
        userService.updateUserAuditStatus(userId, "3", null);
        return JsonUtil.sucess("操作成功");
    }

    @ResponseBody
    @RequestMapping("/getUserStudy")
    public JsonUtil getUserStudy(String userId) {
        JsonUtil result = new JsonUtil();
        if (StringUtils.isBlank(userId)) {
            userId = CommonUtil.getUserId();
        }
        List<SysUserStudyHistory> userStudyHistoryList = getUserStudyOrTrainHistory(userId, "1");
        result.setFlag(true);
        result.setData(userStudyHistoryList);
        return result;
    }

    @ResponseBody
    @RequestMapping("/getUserTrain")
    public JsonUtil getUserTrain(String userId) {
        JsonUtil result = new JsonUtil();
        if (StringUtils.isBlank(userId)) {
            userId = CommonUtil.getUserId();
        }
        List<SysUserStudyHistory> userStudyHistoryList = getUserStudyOrTrainHistory(userId, "2");
        result.setFlag(true);
        result.setData(userStudyHistoryList);
        return result;
    }

    private List<SysUserStudyHistory> getUserStudyOrTrainHistory(String userId, String studyType) {
        List<SysUserStudyHistory> userStudyHistoryList = new ArrayList<>();
        if (StringUtils.isNotBlank(userId)) {
            Example userStudyHistoryExample = new Example(SysUserStudyHistory.class);
            userStudyHistoryExample.and().andEqualTo("suId", userId).andEqualTo("susType", studyType);
            userStudyHistoryExample.setOrderByClause("sus_ind asc");
            userStudyHistoryList = userStudyHistoryService.selectByExample(userStudyHistoryExample);
        }
        return userStudyHistoryList;
    }


    /*
     * 删除个人中心的图片
     * @return
     */
    @RequestMapping(value = "/delUserImage", method = RequestMethod.POST)
    @ResponseBody
    public JsonUtil delUserImage(SupervisorFile file) {
        String type = file.getType();
        String userId = CommonUtil.getUserId();
        if (StringUtil.isBlank(userId) ||  StringUtil.isBlank(type)) {
            return JsonUtil.error("参数获取失败");
        }
        SupervisorFile userFile = new SupervisorFile();
        userFile.setProjectId(userId);
        userFile.setType(type);
        List<SupervisorFile> select = supervisorFileService.select(userFile);
        if (select != null && select.size() > 0) {
            if (select.size() > 10) {
                return JsonUtil.error("失败");
            } else {
                for (int i = 0; i < select.size(); i++) {

                    System.out.println("删除图片 ==========");
                    SupervisorFile supervisorFile = select.get(i);
                    supervisorFileService.deleteByPrimaryKey(supervisorFile.getId());
                }
            }

        } else {
            return JsonUtil.error("失败");
        }
        return JsonUtil.sucess("操作成功");

    }


}
